package com.xuan.yupao.job;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuan.yupao.model.domain.User;
import com.xuan.yupao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class PreCacheUsers {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private UserService userService;

    @Resource
    private RedissonClient redissonClient;

    // 重点推荐用户
    private final List<Long> mainUsersId = Arrays.asList(1L, 2L);


    @Scheduled(cron = "0 2 0 * * ?")
    public void doCacheRecommendUsers() {
        RLock lock = redissonClient.getLock("yupao:user:precache:lock");
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();

        try {
            // 成功获取分布式锁的程序才能进行定时任务
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                log.info("tryLock success: " + Thread.currentThread().getName());
                for (Long userId : mainUsersId) {
                    // TODO 根据当前用户的标签去推荐相关用户
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> page = userService.page(new Page<>(1, 20), queryWrapper);
                    String redisKey = String.format("yupao:user:recommend:userId:%s", userId);

                    try {
                        opsForValue.set(redisKey, page, 1, TimeUnit.DAYS);
                    } catch (Exception e) {
                        log.error("redis set recommend users fail", e);
                    }
                }

            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUsers error", e);
        } finally {
            // 只有当前线程获取到锁后,才能释放该锁
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
                log.info("unlock success: " + Thread.currentThread().getName());
            }
        }
    }

}
